import React, { Component } from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { Form, Icon, Input, Button, Modal, message } from 'antd';
import './Login.scss';
import auth from '../../../actions/auth';
import API from '../../../api/auth';

const FormItem = Form.Item;

class Login extends Component {
  constructor () {
    super();
    this.state = {
      captchaVisible: false,
      verifyEmailVisible: false,
      sendEmailVisible: false,
      emailConfirmLoading: false,
      email: '',
    };
    this.handleLogin = this.handleLogin.bind(this);
    this.handleEmail = this.handleEmail.bind(this);
    this.showEamilModal = this.showEamilModal.bind(this);
    this.handleEmailCancel = this.handleEmailCancel.bind(this);
    this.handleEmailOk = this.handleEmailOk.bind(this);
  }
  /* eslint-disable-next-line react/prop-types */
  componentWillReceiveProps ({ captcha }) {
    this.setState({
      captchaVisible: !!captcha,
    });
  }
  handleLogin = (e) => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        const { username, password, captcha } = values;
        // get captcha from localStorage
        const captchaUUID = (captcha && window.sessionStorage.getItem('captchaUUID')) || undefined;
        this.props.login({
          email: `${username}@pansheng.com`, password, captcha, captchaUUID,
        });
      }
    });
  }
  handleEmail = (e) => {
    this.setState({
      email: e.target.value,
    });
  }
  showEamilModal = () => {
    this.setState({
      verifyEmailVisible: true,
    });
  }
  handleEmailCancel = () => {
    this.setState({
      verifyEmailVisible: false,
    });
  }
  handleEmailOk = async () => {
    const { email } = this.state;
    if (!email) {
      this.warningEmptyEmail();
    } else {
      const params = {
        s: `${email}@pansheng.com`,
      };
      const response = await API.sendResetMail(params);
      if (response.code === 1) {
        this.handleEmailCancel();
        this.setState({
          sendEmailVisible: true,
        });
      } else {
        message.error('邮件发送失败！');
      }
    }
  }
  warningEmptyEmail = () => {
    message.warning('请输入邮箱！');
  }
  confirmEmail = () => {
    this.setState({
      sendEmailVisible: false,
    });
  }
  render () {
    const { getFieldDecorator } = this.props.form;
    const {
      verifyEmailVisible, emailConfirmLoading, sendEmailVisible, email,
    } = this.state;
    return (
      <div className="login-view">
        <div className="left" />
        <div className="right">
          <div className="login-wrapper">
            <img className="logo" src="https://files.pansheng.com/web/ps-logo.png" alt="logo" />
            <div className="label">登录</div>
            <div className="login-form">
              <Form onSubmit={this.handleLogin} className="login-form">
                <FormItem>
                  {getFieldDecorator('username', {
                    rules: [{ required: true, message: '请输入用户名!' }],
                  })(<Input size="large" prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />} placeholder="用户名" addonAfter="@pansheng.com" />)}
                </FormItem>
                <FormItem className="passwordFormItem">
                  {getFieldDecorator('password', {
                    rules: [{ required: true, message: '请输入密码!' }],
                  })(<Input size="large" prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />} type="password" placeholder="密码" />)}
                </FormItem>
                {
                  this.state.captchaVisible ?
                    <div className="captcha-row">
                      <FormItem>
                        {getFieldDecorator('captcha', {
                          rules: [{
                            validator: (rule, value, callback) => {
                              const captcha = value.trim();
                              if (captcha === '') {
                                callback(new Error('请输入验证码'));
                              } else {
                                const reg = /^[A-Za-z0-9]{4}$/;
                                if (!reg.test(captcha)) {
                                  callback(new Error('验证码格式错误'));
                                }
                              }
                              callback();
                            },
                          }],
                        })(<Input size="large" prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />} placeholder="输入右侧验证码" />)}
                      </FormItem>
                      { /* eslint-disable-next-line react/prop-types */ }
                      <img src={this.props.captcha} alt="验证码" />
                    </div>
                  : ''
                }
                <FormItem>
                  <span className="forgetPassword" onClick={this.showEamilModal} role="button" tabIndex="0">忘记密码</span>
                  <Button size="large" type="primary" loading={this.props.loginStatus === 1} htmlType="submit" className="login-form-button">登录</Button>
                </FormItem>
              </Form>
            </div>
          </div>
        </div>
        <Modal
          visible={verifyEmailVisible}
          title="验证邮箱"
          wrapClassName="vertical-center-modal"
          onOk={this.handleEmailOk}
          onCancel={this.handleEmailCancel}
          footer={[
            <Button key="back" onClick={this.handleEmailCancel}>取消</Button>,
            <Button key="submit" type="primary" loading={emailConfirmLoading} onClick={this.handleEmailOk}>确定</Button>,
          ]}
        >
          <div className="email-wrapper">
            <span className="labelEmail">邮箱</span>
            <Input size="large" addonAfter="@pansheng.com" value={email} onChange={this.handleEmail} />
          </div>
        </Modal>
        <Modal
          visible={sendEmailVisible}
          footer={null}
          wrapClassName="vertical-center-modal"
          closable={false}
        >
          <div className="sendEmail">
            <i className="anticon anticon-check-circle icon-success" />
            <p className="prompt-success">邮件已发送至邮箱</p>
            <p>请登录邮箱，查看并点击链接进行验证</p>
            <Button size="large" type="primary" onClick={this.confirmEmail}>确定</Button>
          </div>
        </Modal>
      </div>
    );
  }
}

const mapStateToProps = state => ({
  loginStatus: state.auth.loginStatus,
  captcha: state.captcha.captcha,
});

const mapDispatchToProps = dispatch => ({
  login: (username, password) => dispatch(auth.login(username, password)),
});

Login.propTypes = {
  form: PropTypes.object.isRequired,
  login: PropTypes.func.isRequired,
  loginStatus: PropTypes.number.isRequired,
};

const WrappedNormalLoginForm = Form.create()(Login);

export default connect(mapStateToProps, mapDispatchToProps)(WrappedNormalLoginForm);
